import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { DownOutlined } from '@ant-design/icons';
import {
  Dropdown,
  Menu,
  Modal,
  message,
  Button,
  Form,
  Input,
  Select,
  Row,
  DatePicker,
  Upload,
} from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import {
  profileActivate,
  activitySearch,
  transBatch,
  resetTask,
  editSortid,
  modifyNeedgenasynfile,
  editSortrule,
  assetDetail,
  thirdpartList,
  thirdpartAsset,
  assetEdit,
} from '@/services/activity';
import { queryCount } from '@/services/profile';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import moment from 'moment';
import StorageManager from '@/utils/StorageManager';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
// import { BASE_URL,  } from '@/constants/global.const';
import styles from './style.less';
import { cloneDeep } from 'lodash';

const { RangePicker } = DatePicker;
const { confirm } = Modal;
const { TextArea } = Input;

const enumTypeRule = [
  { label: '按时间段', value: 1 },
  { label: '按星期', value: 2 },
  // { label: '按用户标签', value: 10 },
];

const enumSelectFile = [
  { label: '预付费分表券', value: -3 },
  { label: '营销券', value: -2 },
  { label: '分表券', value: -1 },
  { label: '普通券', value: 0 },
  { label: '异步发放券', value: 1 },
  { label: '打开卡包券', value: 2 },
  { label: '高性能CMT券', value: 3 },
  { label: 'AI发券', value: 4 },
  { label: '高性能导出券', value: 5 },
  { label: '高性能集合券母券', value: 6 },
  { label: '高性能集合券子券', value: 7 },
  { label: '批次券码', value: 12 },
  { label: '调用第三方发码', value: 13 },
  { label: '权益包', value: 14 },
  { label: '权益包的券', value: 15 },
  { label: 'Prime售卖卡', value: 100 },
  { label: 'Prime权益券', value: 101 },
  { label: 'Prime权益', value: 102 },
  { label: 'Prime补权益加油包', value: 103 },
  { label: 'Prime动态SKU', value: 104 },
];

const enumFetchType = [
  { label: '导入三方CDKEY', value: 'REDIS' },
  { label: '接口直连', value: 'API' },
];

const enumCreateType = [
  { label: '直冲到三方账户', value: 'TOP_UP' },
  { label: '兑换码进卡包', value: 'CARD_PACK' },
];

const defaultRuleModel = {
  activityId: '',
  sorttype: 1,
  sortrule: '',
  startTime: '',
  endTime: '',
  value: '',
  week: '',
  userTag: '',
};

const ActivityList: React.FC = () => {
  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');
  const OptionsBrandList = eunmList?.OptionsBrandList || [];
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modelVisible, setModelVisible] = useState<boolean>(false);
  const [ruleVisible, setRuleVisible] = useState<boolean>(false);
  const [assetVisible, setAssetVisible] = useState<boolean>(false);
  const [sortModelVisible, setSortModelVisible] = useState<boolean>(false);
  const [needgenasynfileVisible, setNeedgenasynfileVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [fileUrlBro, setFileUrlBro] = useState<string>();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modalForm] = Form.useForm();
  const [modalSortForm] = Form.useForm();
  const [modalFileForm] = Form.useForm();
  const [modalRuleForm] = Form.useForm();
  const [modalAssetForm] = Form.useForm();
  const sorttypeWatch = Form.useWatch('sorttype', modalRuleForm);
  const fetchTypeWatch = Form.useWatch('fetchType', modalAssetForm);
  const [assetItem, setAssetItem] = useState<any>({});
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [eunmThirdpartList, setEunmThirdpartList] = useState<any>([]);
  const [eunmThirdpartAsset, setEunmThirdpartAsset] = useState<any>([]);
  const [moneyType, setMoneyType] = useState<string>('编辑');
  const [activityIdBro, setActivityIdBro] = useState<string>('');

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.ProfileSearchInfo = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await activitySearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      // const arr: API.ProfileListItem[] = [];
      // rows.forEach((item: any) => {
      //   arr.push({
      //     ...item.realProfileInfo,
      //   });
      // });
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const onChangeThirdPartAssetId = (value: string, options: any) => {
    modalAssetForm.setFieldsValue({
      thirdPartAssetKey: options.thirdPartAssetKey,
      thirdPartAssetValue: options.thirdPartAssetValue,
    });
  };

  const onChangeThirdPartId = async (value: string) => {
    await setEunmThirdpartAsset([]);
    modalAssetForm.setFieldsValue({
      thirdPartAssetId: '',
      thirdPartAssetKey: '',
      thirdPartAssetValue: '',
    });
    const { code, data } = await thirdpartAsset({
      thirdPartId: value,
      brandId: modalAssetForm.getFieldValue('brandId') || assetItem.brandId || '',
    });
    if (code === 200 && data) {
      const arr: any[] = [];
      data.forEach((item: any) => {
        arr.push({
          value: item.id,
          // value: item.thirdPartId,
          label: item.thirdPartKeyName,
          thirdPartAssetKey: item.thirdPartAssetKey,
          thirdPartAssetValue: item.thirdPartAssetValue,
        });
      });
      setEunmThirdpartAsset(cloneDeep(arr));
    }
  };

  const onChangeThirdPartIdBro = async (value: string) => {
    await setEunmThirdpartAsset([]);
    const { code, data } = await thirdpartAsset({
      thirdPartId: value,
      brandId: modalAssetForm.getFieldValue('brandId') || assetItem.brandId || '',
    });
    if (code === 200 && data) {
      // modalAssetForm.setFieldsValue({
      //   thirdPartAssetId: '',
      // });
      const arr: any[] = [];
      data.forEach((item: any) => {
        arr.push({
          value: item.id,
          // value: item.thirdPartId,
          label: item.thirdPartKeyName,
          thirdPartAssetKey: item.thirdPartAssetKey,
          thirdPartAssetValue: item.thirdPartAssetValue,
        });
      });
      setEunmThirdpartAsset(arr);
    }
  };

  const getThirdpartList = async (brandId: string) => {
    const { code, data } = await thirdpartList({
      brandId: brandId,
    });
    if (code === 200 && data) {
      const arr: any[] = [];
      data.forEach((item) => {
        arr.push({
          value: item.thirdPartId,
          label: item.thirdPartName,
        });
      });
      setEunmThirdpartList(arr);
    }
  };

  const onChangeBrandId = (value: string) => {
    getThirdpartList(value);
  };

  // 刷新
  const handleOperate = async (record: any, type: string) => {
    modalAssetForm.setFieldsValue({
      assetId: record.activityId,
      assetName: record.activity + '(CDK)',
      validRangeTime: [moment(record.activityStartTime), moment(record.activityEndTime)],
      brandId: record.brandId,
    });
    getThirdpartList(record.brandId);
    setActivityIdBro(record.activityId);
    if (type === '配置三方资产') {
      const { code, data } = await assetDetail({
        assetId: record.activityId,
      });
      if (code === 200 && data) {
        if (data.id) {
          setMoneyType('编辑');
          onChangeThirdPartIdBro(data.thirdPartId);
          setAssetItem(data);
          setAssetVisible(true);
          modalAssetForm.setFieldsValue({
            ...data,
            assetId: record.activityId,
            assetName: record.activity + '(CDK)',
            validRangeTime: [moment(record.activityStartTime), moment(record.activityEndTime)],
            brandId: record.brandId,
            thirdPartAssetId: data.thirdPartKeyConfigId,
          });
        } else {
          setMoneyType('新增');
          setAssetItem(data);
          setAssetVisible(true);
        }
      }

      return;
    }
    if (type === '排序规则') {
      setRuleVisible(true);
      modalRuleForm.setFieldsValue({
        ...defaultRuleModel,
        activityId: record.activityId,
        sortrule: record.sortrule,
      });
      return;
    }
    if (type === '修改发放标签') {
      setNeedgenasynfileVisible(true);
      modalFileForm.setFieldsValue({
        activityId: record.activityId,
        activity: record.activity,
        needgenasynfile: record.needGenAsynFile,
      });
      return;
    }

    if (type === '权重值') {
      setSortModelVisible(true);
      modalSortForm.setFieldsValue({
        activityId: record.activityId,
        sortId: record.sortId,
      });
      return;
    }

    confirm({
      content: `确认${type}活动：${record.activityId}？`,
      async onOk() {
        if (type === '刷新') {
          const { code, data } = await profileActivate({
            activityIds: record.activityId,
          });
          if (code === 200 && data) {
            message.success('操作成功');
            actionRef?.current?.reloadAndRest?.();
          }
        }
        if (type === '转成批次管理') {
          const { code, data } = await transBatch({
            activityId: record.activityId,
          });
          if (code === 200 && data) {
            actionRef?.current?.reloadAndRest?.();
            confirm({
              content: `转成批次管理成功，是否新增批次？`,
              async onOk() {
                // todo: 跳转到批次管理页
                history.push(`/profile/batchManage/add/${record.activityId}`);
              },
              onCancel() {},
            });
          }
        }
        if (type === '刷新使用规则明细') {
          // 刷新使用规则明细=2.3.12（type=1）
          const { code, data } = await resetTask({
            type: '1',
            activityIds: [record.activityId],
          });
          if (code === 200 && data) {
            message.success('操作成功');
            actionRef?.current?.reloadAndRest?.();
          }
        }
        if (type === '刷新Activity及规则') {
          // 刷新activity及规则=2.2.3 （resetRule=true）
          const { code, data } = await profileActivate({
            activityIds: record.activityId,
            resetRule: true,
          });
          if (code === 200 && data) {
            message.success('操作成功');
            actionRef?.current?.reloadAndRest?.();
          }
        }
      },
      onCancel() {},
    });
  };

  // 生成数量
  const handleQueryCount = async (activityId: string) => {
    const { code, data } = await queryCount({ activityId });
    if (code === 200 && data) {
      confirm({
        title: `当前生成数量:${data.hadGenCount}`,
        okCancel: false,
        okText: '我知道了',
        onOk() {},
      });
    }
  };

  const getItems = (record: API.ProfileListItem) => {
    return (
      <Menu>
        <Menu.Item key="query">
          <a onClick={() => handleQueryCount(record.activityId)}>查询数量</a>
        </Menu.Item>
        {record.needGenAsynFileDesc === '普通券' && (
          <Menu.Item key="batch">
            <a onClick={() => handleOperate(record, '转成批次管理')}>转成批次管理</a>
          </Menu.Item>
        )}
        <Menu.Item key="refresh1">
          <a onClick={() => handleOperate(record, '刷新使用规则明细')}>刷新使用规则明细</a>
        </Menu.Item>
        <Menu.Item key="refresh2">
          <a onClick={() => handleOperate(record, '刷新Activity及规则')}>刷新Activity及规则</a>
        </Menu.Item>
        <Menu.Item key="sort2">
          <a onClick={() => handleOperate(record, '排序规则')}>排序规则</a>
        </Menu.Item>
        <Menu.Item key="sort">
          <a onClick={() => handleOperate(record, '权重值')}>权重值</a>
        </Menu.Item>
        <Menu.Item key="file">
          <a onClick={() => handleOperate(record, '修改发放标签')}>修改发放标签</a>
        </Menu.Item>
        <Menu.Item key="asset">
          <a onClick={() => handleOperate(record, '配置三方资产')}>配置三方资产</a>
        </Menu.Item>
      </Menu>
    );
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '活动定义',
      dataIndex: 'activityId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动代码',
      dataIndex: 'activityCode',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动开始时间',
      dataIndex: 'activityStartTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '活动开始时间',
      },
    },
    {
      title: '活动结束时间',
      dataIndex: 'activityEndTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '活动结束时间',
      },
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '活动定义',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 130,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动代码',
      dataIndex: 'activityCode',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动名称',
      dataIndex: 'activity',
      ellipsis: true,
      width: 180,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动开始时间',
      dataIndex: 'activityStartTime',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动结束时间',
      dataIndex: 'activityEndTime',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '优先级',
      dataIndex: 'sortId',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放标签',
      dataIndex: 'needGenAsynFileDesc',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 120,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => handleOperate(record, '刷新')}>刷新</a>&nbsp;&nbsp;
            <Dropdown overlay={getItems(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </div>
        );
      },
    },
  ];

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleOK = () => {
    modalForm.validateFields().then(async (values) => {
      setConfirmLoad(true);

      if (values.type === '0') {
        const { code, data } = await profileActivate({
          activityIds: values.activityIds,
          resetRule: false,
        });
        if (code === 200 && data) {
          message.success('操作成功');
          modalForm.resetFields();
          setModelVisible(false);
          actionRef?.current?.reloadAndRest?.();
        }
        setConfirmLoad(false);
      } else {
        const { code, data } = await resetTask({
          activityIds: values.activityIds?.split(',') || [],
          type: '0',
        });
        if (code === 200 && data) {
          message.success('操作成功');
          modalForm.resetFields();
          setModelVisible(false);
          actionRef?.current?.reloadAndRest?.();
        }
        setConfirmLoad(false);
      }
    });
  };

  const handleCancel = () => {
    setModelVisible(false);
    modalForm.resetFields();
  };

  const handleSortOK = () => {
    modalSortForm.validateFields().then(async (values) => {
      const { code, data } = await editSortid({
        activityId: values.activityId,
        sortId: values.sortId,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalSortForm.resetFields();
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
      setSortModelVisible(false);
    });
  };

  const handleSortCancel = () => {
    setSortModelVisible(false);
    modalSortForm.resetFields();
  };

  const handleFileOK = () => {
    modalFileForm.validateFields().then(async (values) => {
      const { code, data } = await modifyNeedgenasynfile({
        activityId: values.activityId,
        needgenasynfile: values.needgenasynfile,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalFileForm.resetFields();
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
      setNeedgenasynfileVisible(false);
    });
  };

  const handleFileCancel = () => {
    setNeedgenasynfileVisible(false);
    modalFileForm.resetFields();
  };
  const handleModelAdd = (type: number) => {
    // defaultRuleModel
    const values = modalRuleForm.getFieldsValue();
    if (type === 1) {
      if (!values.startTime) {
        message.error('开始时间不得为空');
        return;
      }
      if (!values.endTime) {
        message.error('结束时间不得为空');
        return;
      }
      if (!values.value) {
        message.error('值不得为空');
        return;
      }
      const str = `${values.startTime}_${values.endTime}_${values.value}`;
      modalRuleForm.setFieldValue('sortrule', values.sortrule ? values.sortrule + ',' + str : str);
    }

    if (type === 2) {
      if (!values.week) {
        message.error('星期不得为空');
        return;
      }

      if (!values.value) {
        message.error('值不得为空');
        return;
      }
      const str = `${values.week}_${values.value}`;
      modalRuleForm.setFieldValue('sortrule', values.sortrule ? values.sortrule + ',' + str : str);
    }
  };

  const handleRuleCancel = () => {
    // setRuleVisible(false);
    // modalRuleForm.resetFields();
    modalRuleForm.setFieldValue('sortrule', '');
  };

  const handleRuleOK = () => {
    setConfirmLoad(true);
    modalRuleForm.validateFields().then(async (values) => {
      const { code, data } = await editSortrule({
        activityId: values.activityId,
        sorttype: values.sorttype,
        sortrule: values.sortrule,
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalRuleForm.resetFields();
        actionRef?.current?.reloadAndRest?.();
      }
      setConfirmLoad(false);
      setRuleVisible(false);
    });
  };

  const handleAssetCancel = () => {
    setAssetVisible(false);
    modalAssetForm.resetFields();
    setEunmThirdpartAsset([]);
  };

  const handleAssetOK = () => {
    modalAssetForm.validateFields().then(async (values) => {
      const params = {
        ...values,
        validStartTime: new Date(values.validRangeTime[0])
          .toISOString()
          .slice(0, 19)
          .replace('T', ' '),
        validEndTime: new Date(values.validRangeTime[1])
          .toISOString()
          .slice(0, 19)
          .replace('T', ' '),
      };
      delete params.validRangeTime;

      // if (values.fetchType === 'REDIS' && !fileUrlBro) {
      //   message.error('请导入资产文件');
      //   return;
      // }

      if (values.fetchType === 'REDIS') {
        params.fileUrl = fileUrlBro;
      }

      if (moneyType !== '编辑') {
        delete params.id;
      }
      setConfirmLoad(true);
      const { code, data } = await assetEdit({
        ...params,
        activityId: activityIdBro,
        // validStartTime: values.validRangeTime[0],
        // validEndTime: values.validRangeTime[1],
      });
      if (code === 200 && data) {
        message.success('操作成功');
        modalAssetForm.resetFields();
        actionRef?.current?.reloadAndRest?.();
        setAssetVisible(false);
        setFileList([]);
        setEunmThirdpartAsset([]);
        setFileUrlBro('');
      }
      setConfirmLoad(false);
    });
  };

  const onFileChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    const { status, response } = file || {};
    setFileList(newFileList);

    // 没有status，说明没有上传，是本地文件
    if (!status) {
      setFileList([...fileList]);
    }
    if (status === 'uploading') {
      setLoading(true);
    }
    if (status === 'done') {
      const { code, data } = response || {};
      if (code === '200' && data) {
        setFileUrlBro(data);
      }
      setLoading(false);
    }
    if (status === 'error') {
      setLoading(false);
      setFileList([...fileList]);
      message.error('上传失败');
    }
  };

  const beforeUploadCrop = (file: File) => {
    const isOverSize = file.size / 1024;
    if (isOverSize > 20 * 1024) {
      message.error('文件大小必须小于20MB!');
      // message.error(`图片大小必须小于${maxSize}kb!`);
      return false;
    }
    return true;
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            // <Button type="primary" key="add" onClick={() => handleCache()}>
            //   刷新缓存
            // </Button>,
            <Button type="primary" key="add" onClick={() => setModelVisible(true)}>
              批量刷新
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="批量刷新activity"
          width={520}
          open={modelVisible}
          onOk={handleOK}
          onCancel={handleCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 5 }}
            form={modalForm}
            initialValues={{
              activityIds: '',
              type: '0',
            }}
          >
            <Form.Item
              label="活动ID"
              name="activityIds"
              rules={[
                {
                  required: true,
                  message: '请输入活动ID',
                },
              ]}
            >
              <TextArea rows={4} placeholder="活动ID,逗号隔开" />
            </Form.Item>
            <Form.Item label="刷新类型" name="type">
              <Select
                options={[
                  {
                    value: '0',
                    label: '0-批量刷新activity',
                  },
                  {
                    value: '1',
                    label: '1-刷新使用规则明细',
                  },
                ]}
              />
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title="修改权重值"
          width={520}
          open={sortModelVisible}
          onOk={handleSortOK}
          onCancel={handleSortCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 5 }}
            form={modalSortForm}
            initialValues={{
              activityId: '',
              sortId: '',
            }}
          >
            <Form.Item
              label="活动ID"
              name="activityId"
              rules={[
                {
                  required: true,
                  message: '请输入活动ID',
                },
              ]}
            >
              <Input disabled={true} />
            </Form.Item>

            <Form.Item
              label="权重值"
              name="sortId"
              rules={[
                {
                  required: true,
                  message: '请输入sortId',
                },
              ]}
            >
              <Input placeholder="sortId" />
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title="修改发放标签"
          width={520}
          open={needgenasynfileVisible}
          onOk={handleFileOK}
          onCancel={handleFileCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 5 }}
            form={modalFileForm}
            initialValues={{
              activityId: '',
              activity: '',
              needgenasynfile: '',
            }}
          >
            <Form.Item label="活动ID" name="activityId">
              <Input disabled={true} />
            </Form.Item>

            <Form.Item label="活动名称" name="activity">
              <Input disabled={true} />
            </Form.Item>

            <Form.Item
              label="发放标签"
              name="needgenasynfile"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={enumSelectFile} />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="修改排序规则"
          width={1020}
          open={ruleVisible}
          onOk={handleRuleOK}
          onCancel={() => {
            modalRuleForm.resetFields();
            setRuleVisible(false);
          }}
          confirmLoading={confirmLoad}
          footer={
            <div>
              <Button type="primary" key="add1" onClick={handleRuleCancel}>
                清除
              </Button>
              <Button type="primary" key="add2" onClick={handleRuleOK}>
                保存
              </Button>
            </div>
          }
        >
          <Form labelCol={{ span: 5 }} form={modalRuleForm} initialValues={defaultRuleModel}>
            <Row align="middle">
              <div style={{ width: 140 }} />
              <Form.Item style={{ width: 300, marginRight: 20 }} label="活动ID" name="activityId">
                <Input disabled={true} />
              </Form.Item>
              <Form.Item style={{ width: 300 }} label="排序类型" name="sorttype">
                <Select
                  options={enumTypeRule}
                  onChange={() => {
                    modalRuleForm.setFieldValue('value', '');
                    modalRuleForm.setFieldValue('sortrule', '');
                  }}
                />
              </Form.Item>
            </Row>

            {sorttypeWatch === 1 && (
              <Row align="middle">
                <div style={{ width: 140 }} />
                <Form.Item
                  style={{ width: 150, marginRight: 20 }}
                  labelCol={{ span: 12 }}
                  label="开始时间"
                  name="startTime"
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  style={{ width: 150, marginRight: 20 }}
                  labelCol={{ span: 12 }}
                  label="结束时间"
                  name="endTime"
                >
                  <Input />
                </Form.Item>

                <Form.Item
                  style={{ width: 150, marginRight: 20 }}
                  labelCol={{ span: 5 }}
                  label="值"
                  name="value"
                >
                  <Input />
                </Form.Item>

                <Button
                  style={{ marginTop: -24 }}
                  type="primary"
                  key="add"
                  onClick={() => handleModelAdd(1)}
                >
                  添加
                </Button>
              </Row>
            )}

            {sorttypeWatch === 2 && (
              <Row align="middle">
                <div style={{ width: 140 }} />
                <Form.Item style={{ width: 300, marginRight: 20 }} label="星期" name="week">
                  <Input />
                </Form.Item>
                <Form.Item
                  style={{ width: 150, marginRight: 20 }}
                  labelCol={{ span: 5 }}
                  label="值"
                  name="value"
                >
                  <Input />
                </Form.Item>

                <Button
                  style={{ marginTop: -24 }}
                  type="primary"
                  key="add"
                  onClick={() => handleModelAdd(2)}
                >
                  添加
                </Button>
              </Row>
            )}

            <Form.Item
              label="排序规则"
              name="sortrule"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Input
                disabled={true}
                placeholder="时间段格式： 1200_1800_8   星期格式：1_20,3_-10   标签格式：暂不支持"
              />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title={moneyType + '配置三方资产'}
          width={520}
          open={assetVisible}
          onOk={handleAssetOK}
          onCancel={handleAssetCancel}
          confirmLoading={confirmLoad}
        >
          {moneyType === '编辑' && (
            <div
              style={{ display: 'flex', justifyContent: 'left', marginBottom: 20, paddingLeft: 60 }}
            >
              {assetItem.fetchType === 'REDIS' && (
                <div style={{ marginRight: 20 }}>
                  已导入：
                  <span style={{ fontSize: 20, fontWeight: 600, color: 'red' }}>
                    {assetItem?.importCount || 0}
                  </span>
                </div>
              )}

              <div style={{ marginRight: 20 }}>
                已发放：
                <span style={{ fontSize: 20, fontWeight: 600, color: 'red' }}>
                  {assetItem?.placeCount || 0}
                </span>
              </div>
              {assetItem.fetchType === 'REDIS' && (
                <div style={{ marginRight: 20 }}>
                  库存量：
                  <span style={{ fontSize: 20, fontWeight: 600, color: 'red' }}>
                    {assetItem?.importCount - assetItem?.placeCount}
                  </span>
                </div>
              )}
            </div>
          )}

          <Form
            labelCol={{ span: 6 }}
            form={modalAssetForm}
            initialValues={{
              id: '',
              assetId: '',
              assetName: '',
              fetchType: 'REDIS',
              creditedType: 'TOP_UP',
              brandId: '',
              brandName: '',
              validRangeTime: [null, null],
              fileUrl: '',
              thirdPartId: null,
              thirdPartAssetId: null,
              thirdPartAssetKey: '',
              thirdPartAssetValue: '',
            }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="资产ID" name="assetId">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item label="资产名称" name="assetName">
              <Input disabled={true} />
            </Form.Item>
            <Form.Item
              label="充值类型"
              name="creditedType"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={enumCreateType} disabled={moneyType === '编辑'} />
            </Form.Item>
            <Form.Item
              label="配置方式"
              name="fetchType"
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
              ]}
            >
              <Select options={enumFetchType} disabled={moneyType === '编辑'} />
            </Form.Item>
            <Form.Item label="品牌号" name="brandId">
              <Select
                disabled={true}
                options={OptionsBrandList}
                placeholder="请选择"
                onChange={onChangeBrandId}
              />
            </Form.Item>
            <Form.Item label="时间范围" name="validRangeTime">
              <RangePicker showTime disabled={true} format={'YYYY-MM-DD HH:mm:ss'} />
            </Form.Item>
            {fetchTypeWatch === 'REDIS' && (
              <Form.Item label="资产导入" name="fileUrl">
                <Upload
                  name="file"
                  accept=".txt"
                  listType={'text'}
                  headers={{
                    ticket: `${StorageManager.getLocalStorageSync('token')}`,
                    contentType: 'multipart/form-data',
                  }}
                  fileList={fileList}
                  action={`${API_CONFIGS.server}${API_CONFIGS.prefix}/thirdpart/upload`}
                  beforeUpload={beforeUploadCrop}
                  onChange={onFileChange}
                >
                  {fileList.length === 0 && (
                    <Button type="primary" loading={loading}>
                      文件上传
                    </Button>
                  )}
                </Upload>
              </Form.Item>
            )}
            {fetchTypeWatch === 'API' && (
              <>
                <Form.Item
                  label="第三方"
                  name="thirdPartId"
                  rules={[
                    {
                      required: true,
                      message: '不得为空',
                    },
                  ]}
                >
                  <Select
                    options={eunmThirdpartList}
                    placeholder="请先选择品牌"
                    onChange={onChangeThirdPartId}
                  />
                </Form.Item>
                <Form.Item
                  label="三方资产内容"
                  name="thirdPartAssetId"
                  rules={[
                    {
                      required: true,
                      message: '不得为空',
                    },
                  ]}
                >
                  <Select
                    options={eunmThirdpartAsset}
                    placeholder="请先选择第三方"
                    onChange={onChangeThirdPartAssetId}
                  />
                </Form.Item>
                <Form.Item label="三方SKU_ID" name="thirdPartAssetKey">
                  <Input disabled={true} />
                </Form.Item>
                <Form.Item label="三方SKU_VALUE" name="thirdPartAssetValue">
                  <Input disabled={true} />
                </Form.Item>
              </>
            )}
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default ActivityList;
